package org.rslai.socket.testtool.config;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.*;

public class LoadXML {

	/**
	 * 读取XML配置文件。输入数据源为字节流。
	 * @param is
	 * @return 返回打开的xml文档
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public Document loadFromXML(InputStream is) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
		DocumentBuilder dombuilder=domfac.newDocumentBuilder();

		Document doc = dombuilder.parse(is);
		return doc ;
	}

	/**
	 * 读取XML配置文件。输入数据源为字节数组。
	 * @param b
	 * @return 返回打开的xml文档
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public Document loadFromXML(byte[] b) throws ParserConfigurationException, SAXException, IOException {
		ByteArrayInputStream bi = new ByteArrayInputStream(b);
		Document doc = loadFromXML(bi);
		return doc ;
	}

	/**
	 * 读取XML配置文件。输入数据源为配置文件名。
	 * @param file
	 * @return 返回打开的xml文档
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public Document loadFromXML(String file) throws ParserConfigurationException, SAXException, IOException {
		InputStream is = null;
		try{
			is = new FileInputStream(new File(file));
			Document doc = loadFromXML(is);
			return doc ;
		} finally {
			try {
				if(is != null) is.close();
			}catch(IOException ix){}
		}
	}

	/**
	 * 读取XML配置文件。输入数据源为URL地址。
	 * @param url
	 * @return　返回打开的xml文档
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public Document loadFromXML(URL url) throws ParserConfigurationException, SAXException, IOException {
		InputStream is = null ;
		try{
			is = url.openStream();
			Document doc = loadFromXML(is);
			return doc ;
		} finally {
			try {
				if(is!=null) is.close();
			} catch(IOException e){}
		}
	}

}